package com.cloudweb.dingding;

import cn.js.fan.db.Conn;
import cn.js.fan.db.ResultIterator;
import cn.js.fan.db.ResultRecord;
import cn.js.fan.util.DateUtil;
import cn.js.fan.util.StrUtil;
import cn.js.fan.web.Global;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.entity.Department;
import com.cloudweb.oa.entity.DeptUser;
import com.cloudweb.oa.security.AuthUtil;
import com.cloudweb.oa.service.IDeptUserService;
import com.cloudweb.oa.service.impl.DeptUserServiceImpl;
import com.cloudweb.oa.utils.SpringUtil;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.db.JdbcTemplate;
import com.cloudwebsoft.framework.util.LogUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceListRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.response.OapiAttendanceListResponse;
import com.google.common.collect.Lists;
import com.redmoon.dingding.service.department.DepartmentService;
import com.cloudweb.dingding.DingDingUtil;
import com.redmoon.oa.dept.DeptDb;
import com.redmoon.oa.dept.DeptUserDb;
import com.redmoon.oa.flow.FormDb;
import com.redmoon.oa.visual.FormDAO;
import com.taobao.api.ApiException;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.dingtalk.api.response.OapiAttendanceListResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.redmoon.dingding.service.auth.AuthService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import static com.cloudweb.dingding.DingDingUtil.getAttendanceList;
import static com.cloudweb.dingding.DingDingUtil.getUserIdByStatus;
import static com.cloudweb.oa.utils.SpringUtil.getUserName;

@Service
@ComponentScan
//@Component
public class AttendDingDing {

    @Autowired
    DeptUserServiceImpl deptUserService;

    @Autowired
    DeptUserDb deptUserDb;
    /**
     * 获取详细的考勤信息
     *
     * @param startWorkDate 起始工作日
     * @param endWorkDate   结束工作日
     * @param userIdList    UserID列表
     * @param isI18n        是否国际化
     * @param statusList    2试用 3在职 5离职 -1无状态
     * @throws ParseException
     */
    public JSONArray getAttendDetails(String startWorkDate,
                                      String endWorkDate,
                                      List<String> userIdList,
                                      boolean isI18n,
                                      String statusList
    ) throws ParseException, SQLException {

        DeptUserServiceImpl deptUserService = new DeptUserServiceImpl();
        DeptUserDb deptUserDb = new DeptUserDb();

        String access_token = AuthService.getAccessToken();
        LogUtil.getLog(AttendDingDing.class).info("access_token:" + access_token);

        JdbcTemplate jt = new JdbcTemplate();
        DeptUserDb deptUser = new DeptUserDb();

        FormDb fd = new FormDb();
        String formCode = "attendancedingding";
        fd = fd.getFormDb(formCode);
        String uintCode = fd.getUnitCode();
        LogUtil.getLog(AttendDingDing.class).info(uintCode);//获取unit_code

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date = formatter.format(now);
        System.out.println(date);

        FormDAO fdao = new FormDAO();

        //所有用户的userId
        List<String> userList = new ArrayList<>();
        userList = userIdList;
        if (userList == null || userList.size() == 0) {
            userList = getUserIdByStatus(statusList);
        } else {
            userList = userIdList;
        }

        //Boolean hasMore = true;//是否下一页
        long offset = 0L;//考勤数据的起始点,下次获取传的offset值为之前的offset+limit
        long limit = 0L;//考勤数据的条数,最大不能超过50条
        int paging = 0;//分页
        PreparedStatement ps = null;
        String connname = Global.getDefaultDB();
        Conn conn = new Conn(connname);

        JSONArray jsonArray = new JSONArray();
        //时间戳转时间格式
        SimpleDateFormat sdfD = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfMs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

        OapiAttendanceListResponse rsp = new OapiAttendanceListResponse();
        int userListSize = userList.size();

        if (userListSize <= 50) {

            limit = 50L;
            do {
                rsp = getAttendanceList(startWorkDate, endWorkDate, userList, offset, limit, isI18n);
                List<OapiAttendanceListResponse.Recordresult> attendanceRecords = rsp.getRecordresult();
                for (OapiAttendanceListResponse.Recordresult record : attendanceRecords) {
                    JSONObject json = new JSONObject();
                    Long recordId = record.getRecordId();//打卡记录ID
                    Long planId = record.getPlanId();//排班ID
                    Long groupId = record.getGroupId();//考勤组ID

                    //String corpId = record.getCorpId();//没有getCorpId()这个方法
                    Long identificationId = record.getId();//唯一标识ID
                    String userId = record.getUserId();//员工ID
                    Date workDate = record.getWorkDate();//考勤日期 Tue Jan 09 11:01:00 CST 2024
                    LogUtil.getLog(AttendDingDing.class).info("考勤日期" + workDate);
                    String workDate1 = sdfS.format(workDate);
                    LogUtil.getLog(AttendDingDing.class).info("考勤日期格式" + workDate1);

                    Date baseCheckTime = record.getBaseCheckTime();//基准时间
                    LogUtil.getLog(AttendDingDing.class).info("基准时间" + baseCheckTime);

                    Date userCheckTime = record.getUserCheckTime();//实际打卡时间
                    String checkType = record.getCheckType();//考勤类型..
                    String timeResult = record.getTimeResult();//打卡结果
                    String locationResult = record.getLocationResult();//位置结果
                    String sourceType = record.getSourceType();//数据来源
                    //sdfD.format(timeStamp)
                    json.put("recordId", recordId);//打卡记录ID
                    json.put("planId", planId);//排班ID
                    json.put("groupId", groupId);//考勤组ID

                    json.put("identificationId", identificationId);
                    json.put("userId", userId);
                    json.put("workDate", sdfD.format(workDate));
                    json.put("baseCheckTime", sdfS.format(baseCheckTime));
                    json.put("userCheckTime", sdfS.format(userCheckTime));
                    json.put("checkType", checkType);
                    json.put("timeResult", timeResult);
                    json.put("locationResult", locationResult);
                    json.put("sourceType", sourceType);

                    String userName = "";
                    String deptCode = "";
                    //List<DeptUser> duList ;
                    Vector<DeptDb> duList ;
                    String sqlName = "select name,realName from users where dingding = " + userId;
                    ResultIterator sqlname = jt.executeQuery(sqlName);
                    if (sqlname.hasNext()) {
                        ResultRecord rr = sqlname.next();
                        userName = rr.getString("name");
                        json.put("userName", userName);

                        duList = deptUserDb.getDeptsOfUser(userName);
                        System.out.println(duList);
                        for (DeptDb du :duList) {
                            deptCode = du.getCode();
                            json.put("dept", deptCode);
                            break;
                        }

//                        duList =  deptUserService.listByUserName(userName);
//                        System.out.println(duList);
//                        for (DeptUser du : duList) {
//                            deptCode = du.getDeptCode();
//                            json.put("dept", deptCode);
//                            break;
//                        }
                        //unitCode = deptUser.getUnitOfUser(rr.getString("realName")).getCode();获取第一个部门的单位
//                        json.put("dept", deptCode);

                    }

                    String sql = "INSERT INTO ft_attendancedingding (unit_code,cws_creator,cws_status,userName,dept,cws_create_date,identificationId,userId, workDate, baseCheckTime,userCheckTime,checkType,timeResult,locationResult,sourceType,recordId,planId,groupId) " +
                            "VALUES ('" + uintCode + "', 'admin' , " + 1 + ",'" + userName + "','" + deptCode + "','" + date + "'," + identificationId + "," + userId + ",'" + sdfD.format(workDate) + "','" + sdfS.format(baseCheckTime) + "','" + sdfS.format(userCheckTime) + "','" + checkType + "','" + timeResult + "','" + locationResult + "','" + sourceType + "'," + recordId + "," + planId + "," + groupId + ")  ";
                    LogUtil.getLog(AttendDingDing.class).info(sql);

                    ps = conn.prepareStatement(sql);
                    conn.executePreUpdate();

//                    ps.close();

                    jsonArray.add(json);
                }

            } while (rsp != null && rsp.getHasMore());
        } else {
            List<String> list;
            for (int i = 0; i < userList.size(); i += 50) {
                list = userList.subList(i - 50, i);
                do {
                    offset = Long.valueOf(paging * 50);
                    limit = limit + 50L;
                    rsp = getAttendanceList(startWorkDate, endWorkDate, list, offset, limit, isI18n);
                    List<OapiAttendanceListResponse.Recordresult> attendanceRecords = rsp.getRecordresult();
                    for (OapiAttendanceListResponse.Recordresult record : attendanceRecords) {
                        JSONObject json = new JSONObject();
                        Long recordId = record.getRecordId();//打卡记录ID
                        Long planId = record.getPlanId();//排班ID
                        Long groupId = record.getGroupId();//考勤组ID

                        //String corpId = record.getCorpId();//没有getCorpId()这个方法
                        Long identificationId = record.getId();//唯一标识ID
                        String userId = record.getUserId();//员工ID
                        Date workDate = record.getWorkDate();//考勤日期
                        Date baseCheckTime = record.getBaseCheckTime();//基准时间
                        Date userCheckTime = record.getUserCheckTime();//实际打卡时间
                        String checkType = record.getCheckType();//考勤类型
                        String timeResult = record.getTimeResult();//打卡结果
                        String locationResult = record.getLocationResult();//位置结果
                        String sourceType = record.getSourceType();//数据来源

                        json.put("recordId", recordId);
                        json.put("planId", planId);
                        json.put("groupId", groupId);

                        json.put("identificationId", identificationId);
                        json.put("userId", userId);
                        json.put("workDate", sdfD.format(workDate));
                        json.put("baseCheckTime", sdfS.format(baseCheckTime));
                        json.put("userCheckTime", sdfS.format(userCheckTime));
                        json.put("checkType", checkType);
                        json.put("timeResult", timeResult);
                        json.put("locationResult", locationResult);
                        json.put("sourceType", sourceType);

                        String userName = "";
                        String deptCode = "";
                        //List<DeptUser> duList ;
                        Vector<DeptDb> duList ;
                        String sqlName = "select name,realName from users where dingding = " + userId;
                        ResultIterator sqlname = jt.executeQuery(sqlName);
                        if (sqlname.hasNext()) {
                            ResultRecord rr = sqlname.next();
                            userName = rr.getString("name");
                            json.put("userName", userName);

                            duList = deptUserDb.getDeptsOfUser(userName);
                            LogUtil.getLog(AttendDingDing.class).info(String.valueOf(duList));
                            for (DeptDb du :duList) {
                                deptCode = du.getCode();
                                json.put("dept", deptCode);
                                break;
                            }

//                        duList =  deptUserService.listByUserName(userName);
//                        System.out.println(duList);
//                        for (DeptUser du : duList) {
//                            deptCode = du.getDeptCode();
//                            json.put("dept", deptCode);
//                            break;
//                        }
                            //unitCode = deptUser.getUnitOfUser(rr.getString("realName")).getCode();获取第一个部门的单位
//                        json.put("dept", deptCode);

                        }

                        String sql = "INSERT INTO ft_attendancedingding (unit_code,cws_creator,cws_status,userName,dept,cws_create_date,identificationId,userId, workDate, baseCheckTime,userCheckTime,checkType,timeResult,locationResult,sourceType,recordId,planId,groupId) " +
                                "VALUES ('" + uintCode + "', 'admin' , " + 1 + ",'" + userName + "','" + deptCode + "','" + date + "'," + identificationId + "," + userId + ",'" + sdfD.format(workDate) + "','" + sdfS.format(baseCheckTime) + "','" + sdfS.format(userCheckTime) + "','" + checkType + "','" + timeResult + "','" + locationResult + "','" + sourceType + "'," + recordId + "," + planId + "," + groupId + ")  ";
                        LogUtil.getLog(AttendDingDing.class).info(sql);
                        ps = conn.prepareStatement(sql);
                        conn.executePreUpdate();

//                    ps.close();

                        jsonArray.add(json);
                    }

                    paging++;
                } while (rsp != null && rsp.getHasMore());
            }
        }

        ps.close();
        return jsonArray;
    }

    public boolean deleteAttendDetails(String startDate, String endDate) {
        try {
            JdbcTemplate jt = new JdbcTemplate();
            String sql = "DELETE FROM ft_attendancedingding WHERE workDate >= '" + startDate + "' and workDate <= '" + endDate + "' ";
            LogUtil.getLog(AttendDingDing.class).info(sql);
            jt.executeUpdate(sql);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void cc() {
        try{

            // LocalDateTime now = LocalDateTime.now();
            // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // String date = formatter.format(now);

            Date now = new Date();
            Date lastDate = DateUtil.addDate(now,-1);
            String yesterday = DateUtil.format(lastDate,"yyyy-MM-dd");
            //String yesterday = "2024-01-09";

            //删除指导区间的打卡记录
            String startDate = yesterday;
            LogUtil.getLog(AttendDingDing.class).info(startDate);
            String endDate = yesterday;
            LogUtil.getLog(AttendDingDing.class).info(endDate);
            com.cloudweb.dingding.AttendDingDing attendDingDing = new com.cloudweb.dingding.AttendDingDing();
            //SpringUtil.getBean(AttendDingDing.class).deleteAttendDetails(startDate, endDate);
            attendDingDing.deleteAttendDetails(startDate, endDate); //true 成功 false 失败
            // boolean isOk = attendDingDing.deleteAttendDetails(startDate,endDate);//true 成功 false 失败

            // if(isOk){
            String startWorkDate = yesterday +" "+ "00:00:01";
            LogUtil.getLog(AttendDingDing.class).info(startWorkDate);
            //console.log(startWorkDate);
            String endWorkDate = yesterday +" "+ "23:59:59";
            //String endWorkDate = "2024-01-16 23:59:59";
            LogUtil.getLog(AttendDingDing.class).info(endWorkDate);
            //console.log("endWorkDate=", endWorkDate);
            List userIdList = new ArrayList();
            //添加用户ID
            //List userIdList = Arrays.asList(new String[]{"1", "2"});
            boolean isI18n = false;
            String statusList = "2,3";

            //SpringUtil.getBean(AttendDingDing.class).getAttendDetails(startWorkDate, endWorkDate, userIdList, isI18n, statusList);
            attendDingDing.getAttendDetails(startWorkDate, endWorkDate, userIdList, isI18n, statusList);
            // }else{
            //     System.out.println("--删除错误--");
            // }
        }catch (Exception e){
            LogUtil.getLog(AttendDingDing.class).error(e);
        }


    }
}
